package com.baomidou.ant.controller;


import com.baomidou.ant.common.Result;
import com.baomidou.ant.entity.*;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@RestController
@RequestMapping("/work-order")
@Api(tags = "工单相关接口")
public class WorkOrderController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private IProcessInfoService processInfoService;
    @Autowired
    private IPinLibraryService pinLibraryService;


    //新增工单接口
    @PostMapping("/add")
    public Result register(@RequestBody RequestRegisterVo requestRegisterVo){
        //判断创建者
        SysUser createUser=userService.getById(requestRegisterVo.getCreateUserId());
        return null;
    }

    //工单查询接口(search)
    @PostMapping("/listOrder")
    public Result listOrder(@RequestBody RequestListOrderVo requestListOrderVo){
        if(requestListOrderVo.getUserId()==null){
            return Result.getFailure().setMsg("请求异常，无法判断权限");
        }
        IPage<ResponseOrderListVo> iPage=workOrderService.orderList(requestListOrderVo);
        return Result.getSuccess().setData(iPage);
    }

    //根据id返回(编辑时)
    @GetMapping("/getOrderById/{id}")
    public Result getOrderById(@PathVariable Integer id){
        WorkOrder workOrder=workOrderService.getById(id);
        ResponseOrderListVo vo=new ResponseOrderListVo();
        BeanUtils.copyProperties(workOrder,vo);
        //连表查询工序名称
        if(workOrder.getNowProcess()==0){
            return Result.getFailure().setMsg("行为禁止！已完工或者待审核！");
        }else
            vo.setNowProcess(processInfoService.getById(workOrder.getNowProcess()).getProcessName());
        return Result.getSuccess().setData(vo);
    }

    //上报时展示信息
    @PostMapping("/getInfoOfReport")
    public Result getInfoOfReport(@RequestBody RequestGetInfoOfReportVo vo){
        WorkOrder workOrder=workOrderService.queryByOrderNum(vo.getOrderNum());
        SysUser sysUser=userService.queryByLoginName(vo.getLoginName());
        ResponseGetInfoOfReportVo responseGetInfoOfReportVo=new ResponseGetInfoOfReportVo();
        responseGetInfoOfReportVo.setOrderNum(workOrder.getOrderNum());
        responseGetInfoOfReportVo.setAmountPlan(workOrder.getAmountPlan());

        return Result.getSuccess().setData(responseGetInfoOfReportVo);
    }


    //工单详情接口(详情时显示)
    @GetMapping("/orderInfo/{id}")
    public Result orderInfo(@PathVariable Integer id){
        WorkOrder workOrder=workOrderService.getById(id);
        ResponseOrderInfoVo vo=workOrderService.getOrderInfo(workOrder);
        return Result.getSuccess().setData(vo);
    }

    //获取工序流程信息接口(详情时显示)
    @GetMapping("/getProcess/{id}")
    public Result getProcess(@PathVariable Integer id){
        List<String> resultList=workOrderService.getProcessName(id);
        return Result.getSuccess().setData(resultList);
    }

    //删除工单接口
    @PostMapping("/delete")
    public Result delete(@RequestBody RequestDeleteVo requestDeleteVo){
        SysUser user=userService.getById(requestDeleteVo.getUserId());
        //如果不是管理员
        if (!Objects.equals(user.getType(), "1")){
            return Result.getFailure().setMsg("您不是超级管理员，无权删除工单");
        }
        //如果是管理员
        if(workOrderService.removeById(requestDeleteVo.getGoalId())){
            return Result.getSuccess().setMsg("删除成功");
        }else{
            return Result.getFailure().setMsg("删除失败");
        }
    }

    //基础信息更新接口
    @PostMapping("/update")
    public Result update(@RequestBody RequestUpdateOrderVo requestUpdateOrderVo){
        if(workOrderService.updateOrder(requestUpdateOrderVo)){
            return Result.getSuccess().setMsg("保存编辑");
        }else{
            return Result.getFailure().setMsg("编辑失败");
        }
    }

    //人员转交接口
    @PostMapping("/updateOfReWorker")
    public Result updateOfReWorker(@RequestBody RequestReWorkerVo vo){
        if(workOrderService.reWorker(vo)){
            return Result.getSuccess().setMsg("保存更改");
        }else{
            return Result.getFailure().setMsg("编辑失败");
        }
    }

    //工单状态判断接口---结束的工单以及没有指派人员的工单不允许进行操作
    @PostMapping("/checkUser")
    public Result checkUser(@RequestBody RequestCheckUserVo vo){
        SysUser user=userService.getById(vo.getUserId());
        WorkOrder workOrder=workOrderService.getById(vo.getOrderId());
        if(Objects.equals(user.getWorkScope(), "0")){
            return Result.getSuccess();
        }else {
            int[] ids = MyStringUtil.toInt(user.getWorkScope());
            List<Integer> idList=Arrays.stream(ids).boxed().collect(Collectors.toList());
            if (idList.contains(workOrder.getNowProcess())) {
                return Result.getSuccess();
            }else
                return Result.getFailure().setMsg("您无权报工该站位!");
        }
    }

    //工单状态判断接口---结束的工单以及没有指派人员的工单不允许进行操作
    @GetMapping("/isOver/{id}")
    public Result isOver(@PathVariable Integer id){
        WorkOrder workOrder=workOrderService.getById(id);
        if (Objects.equals(workOrder.getOrderStatus(), "2")||Objects.equals(workOrder.getOrderStatus(), "1")){
            return Result.getFailure().setMsg("当前工单已经完工，无需上报，上报记录可在<详情>里查看");
        }else
            return Result.getSuccess();
    }

    //工单状态判断接口---是否checkin
    @GetMapping("/isCheck/{id}")
    public Result isCheck(@PathVariable Integer id){
        WorkOrder workOrder=workOrderService.getById(id);
        if(!workOrder.isCheck()){
            return Result.getFailure().setMsg("当前工单未检录,请先投料检录");
        }else
            return Result.getSuccess();
    }

    //工单状态判断接口---审核时判断
    @GetMapping("/isOverOfReport/{id}")
    public Result isOverOfReport(@PathVariable Integer id){
        WorkOrder workOrder=workOrderService.getById(id);
        if (Objects.equals(workOrder.getOrderStatus(), "1")){
            return Result.getSuccess();
        }else if(Objects.equals(workOrder.getOrderStatus(), "2")){
            return Result.getFailure().setMsg("该工单已经完成！");
        }else//0
            return Result.getFailure().setMsg("请等待工单完成...");

    }

    //得到所有总数
    @PostMapping("/getAllTotal")
    public Result getAllTotal(@RequestBody RequestDtoVo requestDtoVo){
        int totalSize=workOrderService.totalSize(requestDtoVo);
        return Result.getSuccess().setData(totalSize);
    }

    //委派通知
    @PostMapping("/myOrderTips")
    public Result myOrderTips(@RequestBody RequestDtoVo requestDtoVo){
        SysUser sysUser=userService.getById(requestDtoVo.getUserId());
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("worker_no",sysUser.getLoginName());
        queryWrapper.eq("order_status",0);
        List<WorkOrder> list=workOrderService.list(queryWrapper);
        if(list.size()==0){
            return Result.getFailure();
        }
        return Result.getSuccess().setData(list.size());
    }

    //人员详情接口
    @GetMapping("/getWorkerInfo/{orderNum}")
    public Result getWorkerInfo(@PathVariable String orderNum){
        WorkOrder workOrder=workOrderService.queryByOrderNum(orderNum);
        ResponseWorkerInfoVo vo=workOrderService.getWorkerInfo(workOrder);
        return Result.getSuccess().setData(vo);
    }

    //未完工序推送
    @GetMapping("/putProcess/{id}")
    public Result putProcess(@PathVariable Integer id){
        WorkOrder workOrder=workOrderService.getById(id);
        List<ResponsePutProcessVo> voList=workOrderService.putProcess(workOrder);
        return Result.getSuccess().setData(voList);
    }

    //根据工序返回对应人员---工序转交或分解的
    @PostMapping("/listWorkerOfProcess")
    public Result listWorkerOfProcess(@RequestBody RequestListWorkerOfProcessVo vo){
        WorkOrder workOrder=workOrderService.getById(vo.getId());
        int[] processIds=MyStringUtil.toInt(workOrder.getProcess());
        String workerNo=null;
        String[] workerNos=workOrder.getAllWorkers().split(";");
        for(int i=0;i<processIds.length;i++){
            //找到选中的id
            if(processIds[i]==vo.getProcessId()){
               workerNo=workerNos[i];
            }
        }
        if(workerNo==null){
            return  Result.getFailure();
        }else
            return Result.getSuccess().setData(workerNo);
    }

    //生产流程单数据
    @GetMapping("/getFlow/{orderNum}")
    public Result getFlow(@PathVariable String orderNum){
        ResponseProductionFlowVo vo=workOrderService.getFlow(orderNum);
        return Result.getSuccess().setData(vo);
    }

    //检录界面打开接口
    @PostMapping("/checkInIt")
    public Result checkInIt(@RequestBody RequestDtoVo vo){
        WorkOrder workOrder=workOrderService.queryByOrderNum(vo.getOrderNum());
        if(workOrder.isCheck()){
            return Result.getFailure();
        }else{
            return Result.getSuccess();
        }
    }

    //检录提交接口
    @PostMapping("/checkIn")
    public Result checkIn(@RequestBody RequestDtoVo vo){
        WorkOrder workOrder=workOrderService.queryByOrderNum(vo.getOrderNum());
        workOrder.setCheck(true);
        workOrder.setCreateNow(LocalDateTime.now());
        if(workOrderService.updateById(workOrder)){
            return Result.getSuccess().setMsg("检录成功");
        }else{
            return Result.getFailure().setMsg("检录失败");
        }
    }

    //批量检录提交接口
    @GetMapping("/batchCheckIn/{orderIds}")
    public Result batchCheckIn(@PathVariable Integer[] orderIds){
        for(int i:orderIds){
            WorkOrder workOrder=workOrderService.getById(i);
            workOrder.setCheck(true);
            workOrder.setCreateNow(LocalDateTime.now());
            workOrderService.updateById(workOrder);
        }
        return Result.getSuccess().setMsg("执行完毕");
    }

    //滞留工单查询接口
    @PostMapping("/retentionOrder")
    public Result retentionOrder(@RequestBody RequestRetentionOrderVo vo){
        IPage<ResponseRetentionOrderVo> iPage=workOrderService.retentionOrder(vo);
        return Result.getSuccess().setData(iPage);
    }

    //站台待产查询接口
    @PostMapping("/inProduction")
    public Result inProduction(@RequestBody RequestInProductionVo vo){
        IPage<ResponseInProductionVo> iPage=workOrderService.inProduction(vo);
        return Result.getSuccess().setData(iPage);
    }

    //恢复列印--单个
    @PostMapping("/reDownOfOne")
    public Result reDownOfOne(@RequestBody RequestOrderNumOfOneVo vo){
        WorkOrder workOrder=workOrderService.queryByOrderNum(vo.getOrderNum());
        if(ObjectUtils.isEmpty(workOrder)){
            return Result.getFailure().setMsg(vo.getOrderNum()+"不存在!");
        }else{
            workOrder.setDown(false);
            if(workOrderService.updateById(workOrder)){
                return Result.getSuccess().setMsg("恢复成功!");
            }else
                return Result.getFailure().setMsg("恢复失败");
        }
    }

    //恢复列印--批量
    @PostMapping("/reDownOfRange")
    public Result reDownOfRange(@RequestBody RequestOrderNumOfRangeVo vo){
        WorkOrder orderOne=workOrderService.queryByOrderNum(vo.getOrderNumMin());
        WorkOrder orderTwo=workOrderService.queryByOrderNum(vo.getOrderNumMax());
        if(ObjectUtils.isEmpty(orderOne)){
            return Result.getFailure().setMsg(vo.getOrderNumMin()+"不存在!");
        }
        if(ObjectUtils.isEmpty(orderTwo)){
            return Result.getFailure().setMsg(vo.getOrderNumMax()+"不存在!");
        }
        String[] orderNums =MyStringUtil.findOrders(vo.getOrderNumMin(),vo.getOrderNumMax());
        for(String orders:orderNums){
            WorkOrder workOrder=workOrderService.queryByOrderNum(orders);
            if(ObjectUtils.isNotEmpty(workOrder)){
                workOrder.setDown(false);
                workOrderService.updateById(workOrder);
            }
        }
        return Result.getSuccess().setMsg("恢复成功!");
    }

    @Autowired
    ICpkInfoService cpkInfoService;
    //工单号下拉框接口
    @PostMapping("/lotSelect")
    public Result lotSelect(@RequestBody RequestDtoVo vo){
        //找到该部门下
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_dept",vo.getDeptId());
        List<WorkOrder> orderList=workOrderService.list(queryWrapper);
        //找到该部门下计算过的cpk记录
        QueryWrapper<CpkInfo> cpkInfoQueryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dept_id",vo.getDeptId());
        List<CpkInfo> cpkInfos=cpkInfoService.list(cpkInfoQueryWrapper);
        //处理结果
        List<String> orderNumList=new ArrayList<>();
        for(CpkInfo cpkInfo:cpkInfos){
            orderNumList.add(cpkInfo.getOrderNum());
        }
        List<ResponseLotSelectVo> voList=new ArrayList<>();
        for(int i=0;i<orderList.size();i++){
            //如果已经计算过不显示
            if(orderNumList.contains(orderList.get(i).getOrderNum())){
                continue;
            }else {
                ResponseLotSelectVo responseLotSelectVo = new ResponseLotSelectVo();
                responseLotSelectVo.setOrderNum(orderList.get(i).getOrderNum());
                voList.add(responseLotSelectVo);
            }
        }
        return Result.getSuccess().setData(voList);
    }

    //lot推送产品
    @GetMapping("/getPin/{orderNum}")
    public Result getPin(@PathVariable String orderNum){
        if(Objects.equals(orderNum, "null") ||ObjectUtils.isEmpty(orderNum)){
            return Result.getFailure();
        }else {
            WorkOrder workOrder = workOrderService.queryByOrderNum(orderNum);
            PinLibrary pin = pinLibraryService.getById(workOrder.getPinId());
            return Result.getSuccess().setData(pin.getPinName());
        }
    }

}
